package com.young.shop.api.controller;


import com.young.shop.api.service.GoodsService;
import com.young.shop.pojo.entity.Goods;
import com.young.shop.pojo.vo.BaseRespVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@RestController
public class GoodsController extends BaseController{

    @Autowired
    private GoodsService goodsService;

    @GetMapping(value = "/goodsIntroduction")
    public BaseRespVO getGoodsById(String id){
        Goods goodsById = goodsService.getGoodsById(id);
        System.out.println(goodsById.getImgUrl());
        return convertSuccessResult(goodsById);
    }

    @GetMapping(value = "/goodsSearch")
    public BaseRespVO queryGoodsByName(String searchKeywords){
        //搜索关键字为空,返回所有
        if (searchKeywords==null){
            List<Goods> allGoods = goodsService.getAllGoods();
            List<Goods> goodsList = removeGoodsByStatus(allGoods);
            return convertSuccessResult(goodsList);
        }
        try {
            List<Goods> goodsList = goodsService.queryGoodsByName(searchKeywords);
            List<Goods> goodsList1 = removeGoodsByStatus(goodsList);
            return convertSuccessResult(goodsList1);
        }catch (RuntimeException e){
            String message = e.getMessage();
            return convertErrorResult(message);
        }
    }


    //讲状态值为   已下架   的商品从商品集合中删除
    public List<Goods> removeGoodsByStatus(List<Goods> list){
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getStatus() == 0){
                list.remove(i);
                --i;
            }
        }
        return list;
    }


}
